package yxy.cherry.paycenter.servlet.channel.vivo_quick;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jodd.util.StringUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.util.TextUtils;
import yxy.apple.logger.Logger;
import yxy.apple.util.*;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.charge;
import yxy.cherry.game.base.bean.SDKParm;
import yxy.cherry.game.base.bean.SdkParmEnum;
import yxy.cherry.paycenter.channelmodule.ActType;
import yxy.cherry.paycenter.channelmodule.sdk_huawei_quick.PayMoudle_huawei_quick;
import yxy.cherry.paycenter.channelmodule.sdk_vivo_quick.PayMoudle_vivo_quick;
import yxy.cherry.paycenter.database.dao.orderinfoDao;
import yxy.cherry.paycenter.database.dao.ordersDao;
import yxy.cherry.paycenter.database.db.orderinfo;
import yxy.cherry.paycenter.database.db.orders;
import yxy.cherry.paycenter.servlet.channel.Servlet;
import yxy.cherry.paycenter.util.HttpUtil;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.channel.SdkChannel;
import yxy.game.pm2.bean.db.sdk.SDK_UnionChannel;
import yxy.game.pm2.bean.db.sdk.SDK_UnionChannelDAO;
import yxy.game.pm2.bean.module.OrderInfoModule;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.EOFException;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
import java.util.*;

//vivo快游戏，支付结果通知
public class Servlet_vivo_quick extends Servlet{
	private static final Logger logger = Logger.create(Servlet_vivo_quick.class);
	@Override
	public String getChannel() {
		return SdkChannel.sdk_vivo_quick;
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//参考文档：
		// https://minigame.vivo.com.cn/documents/#/api/service/newpay?id=sign
		JSONObject rjson = new JSONObject();
		String SUCCESS = "success";
		String FAIL = "fail";
		try {
			HttpUtil.printlnParseMap("post", req);
			JSONObject json = HttpUtil.getParseJSON(req);
			logger.info(SdkChannel.sdk_vivo_quick + ":notify:" + json);

			String respCode = json.getString("respCode");
			String respMsg = json.getString("respMsg");
			String signMethod = json.getString("signMethod"); //对关键信息进行签名的算法名称：MD5
			String signature = json.getString("signature");
			String tradeType = json.getString("tradeType");
			String tradeStatus = json.getString("tradeStatus");
			String cpId = json.getString("cpId");
			String appId = json.getString("appId");
			String uid = json.getString("uid");
			String cpOrderNumber = json.getString("cpOrderNumber"); //我方订单号
			String orderNumber = json.getString("orderNumber");
			String orderAmount = json.getString("orderAmount"); //分
			String extInfo = json.getString("extInfo");
			String payTime = json.getString("payTime");

			logger.info("respCode:%s", respCode);

			//基础参数校验
			if (!"200".equals(respCode)) throw new Exception("notify结果异常");
			if (StringUtil.isAllEmpty(appId, uid, cpOrderNumber, orderAmount))
				throw new Exception("参数异常");

			//myorderid 为空
			if(cpOrderNumber != null && !cpOrderNumber.equals("")) {
				orderinfo oinfo = new orderinfo();
				oinfo.setMyorderid(cpOrderNumber);
				oinfo.setOtherinfo(json.toString());
				orderinfoDao.add(oinfo);
			}

			//渠道参数核对
			SDK_UnionChannel unionChannel = SDK_UnionChannelDAO.getByAppId(SdkChannel.sdk_vivo_quick, appId);
			if (unionChannel == null) throw new Exception("渠道异常");
			//订单状态 不成功的订单不处理
			if (!"0000".equals(tradeStatus)) throw new Exception("order status error");
			//订单核对，是否存在
			orders o = ordersDao.getOrderByMyorderid(cpOrderNumber);
			if (o == null) throw new Exception("订单不存在");
			//已经是成功的订单，不用重复处理
			if (o.getOrderstate() == 1) {
				returnInfo(SUCCESS, resp);
				return;
			}
			//金额核对
			int fee = Integer.parseInt(orderAmount);
			if (fee != o.getGoodsprice()) throw new Exception("amount error");

			//sign校验
			Map<String, String> params = json.toJavaObject(Map.class);
			params.remove("signMethod");
			params.remove("signature");
			logger.info(SdkChannel.sdk_vivo_quick + ":params:%s", JSON.toJSON(params));
			String signContent = SdkUtil.mapToContent(params, false);
			signContent += "&" + MD5Utility.MD5(unionChannel.getPrivateKey()).toLowerCase();
			logger.info(SdkChannel.sdk_vivo_quick + ":signContent:%s", signContent);
			String makeSign = MD5Utility.MD5(signContent).toLowerCase();
			logger.info(SdkChannel.sdk_vivo_quick + ":makeSign:%s", makeSign);

			if (!makeSign.equals(signature)) throw new Exception("sign error");


			o.setPlatorderid(orderNumber);
			o.setUpdatetime(new Date());
			o.setPayamount(fee);
			o.setOrderstate(OrderInfoModule.orderinfofinish);
			ordersDao.update(o);

			ActType at = ActType.getat(o.getActtype());
//		PayType pt = PayType.getpt(at.getPaytype());
			PayMoudle_vivo_quick am = new PayMoudle_vivo_quick();
			ArrayList<Currency> curs = am.getRewardInfoByType(o.getPlayercode(), at, o.getGoodsid());

			charge charge = DataCenter.getData(o.getGoodsid(), charge.class);
			am.createOrderInfoModule(o, curs, charge.getVipexp(), o.getGoodsprice());

			returnInfo(SUCCESS, resp);
		} catch (Exception e) {
			logger.error(SdkChannel.sdk_vivo_quick + ":sign error:%s", e);
			e.printStackTrace();
			returnInfo(FAIL, resp);
		}
	}
}
